from collections import Counter
import random
from getGBest import getPosition
import numpy as np


def checkArchive(archive, arFits, nAr, M):
    """检查archive集是否超出了规模。如果超出了规模那么采取减少操作.
    Params:
        :param archive:
        :param arFits:
        :param nAr: archive集合的最大规模 100
        :param M:
        :return:
    """
    if archive.shape[0] <= nAr:
        return archive, arFits
    else:
        nA = archive.shape[0]  # 当前解集大小 
        flags = getPosition(arFits, M)
        # 统计每个网格出现的次数 <class 'tuple'>: (2404.0, 2)..
        counts = Counter(flags).most_common()
        # 选择原始archive集
        isCh = np.array([True for i in range(nA)])
        indices = np.arange(nA)  # 原始索引  
        for i in range(len(counts)):
            # 对于粒子数多于1个的网格，按照下面的计算公式删除粒子数PN
            if counts[i][-1] > 1:
                # 删除当前网格counts[i][0]的粒子数 （计算公式）
                pn = int((nA - nAr) / nA * counts[i][-1] + 0.5)
                # 当前要删除的网格中的所有粒子的索引 
                gridIdx = indices[flags == counts[i][0]].tolist()
                # 在网格k中,随机删除PN个粒子
                pIdx = random.sample(gridIdx, pn)
                isCh[pIdx] = False  # 删除这些元素 
        archive = archive[isCh]
        arFits = arFits[isCh]
        return archive, arFits


if __name__ == "__main__":
    counts = np.array([(1, 2), (8, 9)])
    # 2
    # 9
    print(counts[0][-1])
    print(counts[1][-1])
    print("--------------------")
    pn = 1
    gridIdx = np.array([23, 42, 20]).tolist()
    # 从gridIdx中随机抽取pn个数据
    pIdx = random.sample(gridIdx, pn)
    print(pIdx)
